package com.opentool.web.runner;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
@Component
@Order(1)
@Slf4j
public class SqlliteRunner implements ApplicationRunner {

    @Value("${server.sqllite.db.path}")
    private String dbPath;

    @Override
    public void run(ApplicationArguments applicationArguments) throws Exception {
        InputStream sqlIs=null;
        Connection connection=null;
        Statement statement=null;
        try {
            File file=new File(dbPath);
            if(file.exists()){
                log.info(String.format("数据库已存在[%s]",dbPath));
                return;
            }else{
                file.getParentFile().mkdirs();
            }
            log.info(String.format("初始化数据库[%s]",dbPath));
            Class.forName("org.sqlite.JDBC");
            connection = DriverManager.getConnection("jdbc:sqlite:" + dbPath);
            statement = connection.createStatement();
            Resource sqlResource=new ClassPathResource("sql/init.sql");
            sqlIs=sqlResource.getInputStream();
            String sql=IOUtils.toString(sqlIs);
            statement.executeUpdate(sql);
            log.info(String.format("初始化数据库---成功[%s]",dbPath));
        }catch (Exception e){
            log.warn(String.format("初始化数据库---异常[%s]",dbPath),e);
        }finally {
            try { sqlIs.close();}catch (Exception e){}
            try { statement.close();}catch (Exception e){}
            try { connection.close();}catch (Exception e){}
        }
    }
}
